#!/usr/bin/python

import sys,getopt
import commands
import textwrap
import calendar
import JoSelect
import JoStore
import JoTime
import JoPrint
import JoSql
import JoDef
import time
import re
import os

def usage():
	return """
    usage: jostat [options] datestr
    datestr is day or date for the end of the duration specified 
    by --type

    Options:
    -t,--tag=TAG    only include tasks that contain these tag(s),
                    separate multiple tags with ','
    -m,--type=TYPE  type of report to create, types are daily, weekly, 
                    biweekly and monthly, default is weekly

    examples:
        ./jostat.py thu
        ./jostat.py --type=weekly 2/28
        ./jostat.py --tag=work --type=biweekly fri
	"""

def main():

	opts = [("tag","t"),("type","m")]
	options = JoStore.jostore(usage(),opts)
	try: 
		args = options.parse_args(sys.argv[1:])
	except getopt.GetoptError:
		print usage()
		sys.exit()

	JOUSER = os.getenv("JOUSER","")
	datestr = None
	range = None
	if len(args) == 1:
		datestr = args[0]
	if options.type:
		range = options.type
	(st,en) = JoTime.date_range(datestr,range,17)
	header = JoTime.print_time(st)+" to "+JoTime.print_time(en)
	header = re.sub("  "," ",header)
	selects = ("descr","workframe")
	where = "where workframe.time is not null"
	tagl = None
	if( options.tag ):
		tagl = options.tag.split(",")
	sql = JoSelect.mergeselect(selects,(st,en),tagl,where,None,None)

	sw = JoDef.JOPREF_SCREENWIDTH
	table = JoSql.sql_table(sql,JOUSER,(3,))
	cols = [ (0,"%4s",6),(2,"%s",50),(3,"%3.0f hours spent",20) ]	
	rv =  "-"*sw + os.linesep
	rv +=  header.center(sw) + os.linesep
	rv +=  "-"*sw + os.linesep
	
	tbl = JoPrint.tablespec(table,colpad=1,rowpad=0)
	tbl.addcol(0,width=6,justify='left')
	tbl.addcol(2,width=56,justify='left')
	tbl.addcol(3,width=12,justify='right',type='float',format='%.1f hours')
	tbl.addrow('last')
	tbl.addcol(0,row='last',width=sw,format='-'*sw,colpad=os.linesep)
	tbl.addcol(0,row='last',width=6,justify='left',format='')
	tbl.addcol(2,row='last',width=56,justify='right',format="Total")
	tbl.addcol(3,row='last',width=12,justify='right',type='float',format='%.1f hours')
	rv += tbl.printtable()
	print rv

if __name__ == "__main__":
    main()
